package popcorn.ticket.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import popcorn.ticket.entity.Logs;
import popcorn.ticket.entity.Movies;
import popcorn.ticket.entity.MoviesExample;
import popcorn.ticket.entity.Users;
import popcorn.ticket.service.LogsService;
import popcorn.ticket.service.MovieService;
import popcorn.ticket.service.OssService;
import popcorn.ticket.tool.AjaxResponse;
import popcorn.ticket.tool.PageData;

@Controller
@MultipartConfig
public class MovieController {

	@Autowired
	private MovieService ms;
	@Autowired
	private OssService os;
	@Autowired
	private LogsService ls;
	
	Logger logger = Logger.getLogger(MovieController.class);

	/**
	 * 后台分页查询
	 * @param page
	 * @param pagesize
	 * @param key
	 * @param select
	 * @return
	 */
	@RequestMapping("Movie")
	@ResponseBody
	public PageData<Movies> getMovie(@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "pagesize", defaultValue = "10") int pagesize,
			@RequestParam(name = "key", defaultValue = "") String key,
			@RequestParam(name = "select", defaultValue = "电影名") String select) {
		
		MoviesExample example = new MoviesExample();
		if ("电影名".equals(select)) {
			example.createCriteria().andMovienameLike("%" + key + "%");
		} else if ("地区".equals(select)) {
			example.createCriteria().andPlaceLike("%" + key + "%");
		} else if ("语言".equals(select)) {
			example.createCriteria().andLanguageLike("%" + key + "%");
		} else if ("主演".equals(select)) {
			example.createCriteria().andMainactorLike("%" + key + "%");
		} else if ("导演".equals(select)) {
			example.createCriteria().andDirectorLike("%" + key + "%");
		} else if ("简介".equals(select)) {
			example.createCriteria().andMovieinfoLike("%" + key + "%");
		}
		return ms.selectByExample(example, page, pagesize);
	}
	
	
	/**
	 * 前台查正在上映  -- 模糊
	 * @param page
	 * @param key
	 * @param select
	 * @return
	 */
	@RequestMapping("MovieByUser")
	@ResponseBody
	public List<Movies> getMovieByUser(@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "key",defaultValue = "")String key,
			@RequestParam(name = "select",defaultValue = "电影名")String select) {
		
		PageHelper.startPage(page, 3);
		Movies movie = new Movies();
		List<Movies> list = null;
		if ("电影名".equals(select)) {
			movie.setMoviename(key);
			list = ms.selMoviesByLike(movie);
		} else if ("地区".equals(select)) {
			movie.setPlace(key);
			list = ms.selMoviesByLike(movie);
		} else if ("语言".equals(select)) {
			movie.setLanguage(key);
			list = ms.selMoviesByLike(movie);
		} else if ("主演".equals(select)) {
			movie.setMainactor(key);
			list = ms.selMoviesByLike(movie);
		} else if ("导演".equals(select)) {
			movie.setDirector(key);
			list = ms.selMoviesByLike(movie);
		} else if ("类型".equals(select)) {
			list = ms.selMoviesByTypename(key);
		}
		return list;
	}
	
	@RequestMapping("MovieByOrder")
	@ResponseBody
	public List<Movies> getMovieByOrder(String factor,int page){
		
		PageHelper.startPage(page, 3);
		List<Movies> list = null;
		// 全部 -- 根据movieid 
		if(factor.equals("all")) {
			list = ms.selMoviesByOrder("movieId");
		}
		// 上映 -- 根据releasedate
		else if(factor.equals("release")){
			list = ms.selMoviesByOrder("releaseDate");
		}
		// 人气 -- 根据票数 t
		else if(factor.equals("popularity")) {
			list = ms.selMoviesByOrder("COUNT(ticket.ticketId)");
		}
		// 影评数  -- 根据影评 m
		else if(factor.equals("comments")) {
			list = ms.selMoviesByOrder("COUNT(moviecomment.commentId)");
		}
		return list;
	}
	
	
	@RequestMapping("MovieLikeCount")
	@ResponseBody
	public int countMovieLike(@RequestParam(name = "key",defaultValue = "")String key,
			@RequestParam(name = "select",defaultValue = "电影名")String select) {
		Movies movie = new Movies();
		List<Movies> list = new ArrayList<Movies>();
		if ("电影名".equals(select)) {
			movie.setMoviename(key);
			list = ms.selMoviesByLike(movie);
		} else if ("地区".equals(select)) {
			movie.setPlace(key);
			list = ms.selMoviesByLike(movie);
		} else if ("语言".equals(select)) {
			movie.setLanguage(key);
			list = ms.selMoviesByLike(movie);
		} else if ("主演".equals(select)) {
			movie.setMainactor(key);
			list = ms.selMoviesByLike(movie);
		} else if ("导演".equals(select)) {
			movie.setDirector(key);
			list = ms.selMoviesByLike(movie);
		} else if ("类型".equals(select)) {
			list = ms.selMoviesByTypename(key);
		}
		logger.debug("list:"+list.size());
		PageInfo<Movies> pi = new PageInfo<Movies>(list);
		return (int)pi.getTotal();
	}
	
	@RequestMapping("MovieByOrderCount")
	@ResponseBody
	public int countMovieByOrder(String factor){
		List<Movies> list = null;
		// 全部 -- 根据movieid 
		if(factor.equals("all")) {
			list = ms.selMoviesByOrder("movieId");
		}
		// 上映 -- 根据releasedate
		else if(factor.equals("release")){
			list = ms.selMoviesByOrder("releaseDate");
		}
		// 人气 -- 根据票数 t
		else if(factor.equals("popularity")) {
			list = ms.selMoviesByOrder("COUNT(ticket.ticketId)");
		}
		// 影评数  -- 根据影评 m
		else if(factor.equals("comments")) {
			list = ms.selMoviesByOrder("COUNT(moviecomment.commentId)");
		}
		PageInfo<Movies> pi = new PageInfo<Movies>(list);
		
		return (int)pi.getTotal();
	}
	
	String msg = "失败";
	int code = 0;

	/**
	 * 添加电影
	 * @param movie
	 * @param mdate
	 * @param upload
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("addMovie")
	@ResponseBody
	public AjaxResponse addMovie(Movies movie, String mdate, MultipartFile upload)
			throws IOException, ServletException {

		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		Date release = null;
		try {
			release = s.parse(mdate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		movie.setReleasedate(release);
		movie.setMoviestatus(1);

		String url = os.uploadPicFile(upload, movie.getMoviename());

		movie.setMoviepicture(url);
		boolean flag = ms.insert(movie) > 0;
		if (flag) {
			msg = "添加成功";
			code = 200;
			return ar(msg, code);
		}
		return ar("成功", code);
	}

	/**
	 * 更新电影
	 * 
	 * @param movie
	 * @return
	 */
	@RequestMapping("updmovie")
	@ResponseBody
	public AjaxResponse UpdMovie(@RequestBody Movies movie) {

		boolean flag = ms.updateByPrimaryKeySelective(movie) > 0;
		if (flag) {
			msg = "修改成功";
			code = 200;
			// 日志记录 禁播电影
			if (movie.getMoviestatus() == 3) {
				Logs logs = new Logs();
				try {
					logs.setLogip(InetAddress.getLocalHost() + "");
					logs.setLogobject("movies");
					logs.setLogop("修改");
					logs.setLogtime(new Date());
					logs.setRemark("电影" + movie.getMoviename() + "被禁播");
					Users u = new Users();
					u.setUserid(1);
					logs.setUsers(u);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ls.insertLogs(logs);
			}
			return ar(msg, code);
		}
		return ar(msg, code);
	}

	/**
	 * 视频上传
	 * @param movie
	 * @param videoupload
	 * @return
	 */
	@RequestMapping("addVideo")
	@ResponseBody
	public AjaxResponse addVideo(Movies movie, MultipartFile videoupload) {

		String url = os.uploadViedoFile(videoupload, movie.getMoviename());
		if (url != null) {
			movie.setMovievideo(url);
			boolean flag = ms.updateByPrimaryKeySelective(movie) > 0;
			if (flag) {
				msg = "上传成功";
				code = 200;
				return ar(msg, code);
			}
		}
		return ar(msg, code);
	}

	/**
	 * 修改电影图片
	 * @param movie
	 * @param uploadPic
	 * @return
	 */
	@RequestMapping("updMoviePic")
	@ResponseBody
	public AjaxResponse updPic(Movies movie, MultipartFile uploadPic) {

		String url = os.uploadPicFile(uploadPic, movie.getMoviename());
		if (url != null) {
			movie.setMoviepicture(url);
			boolean flag = ms.updateByPrimaryKeySelective(movie) > 0;
			if (flag) {
				msg = "修改成功";
				code = 200;
				return ar(msg, code);
			}
		}
		return ar(msg, code);
	}

	public AjaxResponse ar(String msg, int code) {
		AjaxResponse ar = new AjaxResponse(msg, code);
		return ar;
	}

	/**
	 * 获取今天推荐的影片
	 * @return
	 */
	@GetMapping(value = "getmOK", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> sltODList() {
		return ms.getMoviesOK();
	}

	/**
	 * 通过电影编号查询该电影的票数
	 * @param movieId
	 * @return
	 */
	@GetMapping(value = "getmtnum", produces = "application/json;charset=utf-8")
	@ResponseBody
	public int sltMTicketNum(int movieId) {
		return ms.getMTicketNum(movieId);
	}

	/**
	 * 通过电影编号查询该电影的类型
	 * @param movieId
	 * @return
	 */
	@GetMapping(value = "getmtypes", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> getMType(int movieId) {
		return ms.getMType(movieId);
	}

	/**
	 * 查询今日排行的电影
	 * @return
	 */
	@GetMapping(value = "getmtoday", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> getMToday() {
		return ms.getMoviesToday();
	}

	/**
	 * 今日放映的电影（前四名）
	 * @return
	 */
	@GetMapping(value = "getmtodayfour", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> getMTodayFour() {
		return ms.getMoviesTodayFour();
	}
	
	/**
	 * 通过电影编号查询影评分数
	 * @param movieId
	 * @return
	 */
	@GetMapping(value = "getmscore", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> getMScore(int movieId) {
		return ms.getMScore(movieId);
	}
	
	@RequestMapping(value = "glbo", produces = "application/json;charset=utf-8")
	@ResponseBody
	public PageData<Movies> getListByOrder(@RequestParam(value = "page", defaultValue = "1") int page) {
		PageData<Movies> pd = ms.getListByOrder(page);
		return pd;
	}
	
	//详情页
	//通过电影编号查询电影详细信息
	@GetMapping(value = "getminfo", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Movies getMInfo(int movieId) {
		return ms.getMInfo(movieId);
	}
	
	/**
	 * 联想查询
	 * 
	 * @param movies
	 * @return
	 */
	@RequestMapping(value = "gws", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List getWithSearch(Movies movies) {
		logger.info("movies:"+movies.getmTypeName());
		List list = ms.getListWithSearch(movies);
		return list;
	}

	/**
	 * 联想模糊查询
	 * 
	 * @param page
	 * @param keywords
	 * @param movies
	 * @return
	 */
	@PostMapping(value = "smbl", produces = "application/json;charset=utf-8")
	@ResponseBody
	public PageData<Movies> selectMoviesByLike(
			@RequestParam(value = "page", defaultValue = "1", required = false) int page,
			@RequestParam(value = "keywords", defaultValue = "") String keywords,
			@RequestParam(value = "movies", defaultValue = "") String movies) {
	
		PageData<Movies> pd = null;
		Movies mv = new Movies();
		if (movies.equals("mTypeName")) {
			mv.setmTypeName("1");
			pd = ms.selectMoviesByLikeWTN(page, keywords, mv);
		} else {
			if (movies.equals("moviename")) {
				mv.setMoviename("1");
			} else if (movies.equals("director")) {
				mv.setDirector("1");
			} else if (movies.equals("mainactor")) {
				mv.setMainactor("1");
			} else if (movies.equals("place")) {
				mv.setPlace("1");
			} else if (movies.equals("language")) {
				mv.setLanguage("1");
			}
			 pd = ms.selectMoviesByLike(page, keywords, mv);
		}
		
		return pd;
	}
	
	/**
	 * 联想模糊查询+电影的状态
	 * @param page
	 * @param keywords
	 * @param movies
	 * @return
	 */
	@PostMapping(value = "getmsl", produces = "application/json;charset=utf-8")
	@ResponseBody
	public PageData<Movies> selectMLikeAndStatus(
			@RequestParam(value = "page", defaultValue = "1", required = false) int page,
			@RequestParam(value = "keywords", defaultValue = "") String keywords,
			@RequestParam(value = "movies", defaultValue = "") String movies,
			@RequestParam(value = "moviestatus", defaultValue = "0") int moviestatus) {

		PageData<Movies> pd = null;
		
		Movies mv = new Movies();
		//判断他的类型
		if (movies.equals("mTypeName")) {
			mv.setmTypeName("1");
			if (moviestatus!=0) {
				mv.setMoviestatus(moviestatus);
			}
			pd = ms.getMtypeLikeAndStatus(page, keywords, mv, moviestatus);
			
		} else {
			if (movies.equals("moviename")) {
				mv.setMoviename("1");
				if (moviestatus!=0) {
					mv.setMoviestatus(moviestatus);
				
				}
			} else if (movies.equals("director")) {
				mv.setDirector("1");
				if (moviestatus!=0) {
					mv.setMoviestatus(moviestatus);
				}
			} else if (movies.equals("mainactor")) {
				mv.setMainactor("1");
				if (moviestatus!=0) {
					mv.setMoviestatus(moviestatus);
				}
			} else if (movies.equals("place")) {
				mv.setPlace("1");
				if (moviestatus!=0) {
					mv.setMoviestatus(moviestatus);
				}
			} else if (movies.equals("language")) {
				mv.setLanguage("1");
				if (moviestatus!=0) {
					mv.setMoviestatus(moviestatus);
				}
			}
			pd = ms.getMLikeAndStatus(page, keywords, mv, moviestatus);
		}
		
		return pd;
	}

	//获取即将上映的评分排行榜
	@GetMapping(value = "getmsoon", produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<Movies> getMoviesSoon() {
		return ms.getMoviesSoon();
	}

	
	
}
